package json;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.json.JSONObject;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2)
@Measurement(iterations = 3) // 10 iterations, 10s each
@Fork(1)
@State(Scope.Benchmark)
public class JsonParseJMH {
    static ObjectMapper mapper = new ObjectMapper();

    final static String s = "{\"type\":\"duration\",\"sub_type\":\"concrete\",\"start\":\"2019-09-10T05:00:00\",\"end\":\"2019-09-10T17:00:00\",\"grain\":\"arbitrary\",\"festival_flag\":false,\"token\":\"明天上午五点到下午五点\",\"start_timestamp\":1568062800000,\"end_timestamp\":1568106000000}";

    @Benchmark
    public JsonNode jackson() throws IOException {
        return mapper.reader().readTree(s);
    }

    @Benchmark
    public JSONObject orgJson() {
        JSONObject node = new JSONObject(s);
        return node;
    }

    @Benchmark
    public JsonElement gson() {
        return JsonParser.parseString(s);
    }

    public static void main(String[] args) throws RunnerException {
        final Options options = new OptionsBuilder()
                .include(".*" + JsonParseJMH.class.getSimpleName() + ".*")
                .forks(1)
                .build();

        new Runner(options).run();
    }
}
